package com.zhouyu.az_service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.zhouyu.entity.DemoData;
import com.zhouyu.mapper.UserMapper;
import com.zhouyu.utils.TestFileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author lipengze
 * @version 1.0
 * @description: TODO
 * @date 2024/11/28 11:19
 */
@Slf4j
@Service
public class ExcelService {
    @Resource
    private UserMapper userMapper;


    private List<DemoData> data(Integer pageSize) {
        List<DemoData> list = ListUtils.newArrayList();
        for (int i = 0; i < pageSize; i++) {
            DemoData data = new DemoData();
            data.setId(Long.parseLong(i+""));
            data.setName("name"+i);
            data.setAge(i);
            data.setSex("男");
            list.add(data);
        }
        return list;
    }
    public void export() {
        long t1 = System.currentTimeMillis();

        // 方法2: 如果写到不同的sheet 同一个对象
        String fileName = TestFileUtil.getPath() + "repeatedWrite" + System.currentTimeMillis() + ".xlsx";
        // 这里 指定文件
        try (ExcelWriter excelWriter = EasyExcel.write(fileName, DemoData.class).build()) {
            // 去调用写入,这里我调用了五次，实际使用时根据数据库分页的总的页数来。这里最终会写到5个sheet里面
            for (int i = 0; i < 5; i++) {
                // 每次都要创建writeSheet 这里注意必须指定sheetNo 而且sheetName必须不一样
                WriteSheet writeSheet = EasyExcel.writerSheet(i, "模板" + i).build();
                // 分页去数据库查询数据 这里可以去数据库查询每一页的数据
                List<DemoData> data = data(10000);
                excelWriter.write(data, writeSheet);
            }
        }
        long t2 = System.currentTimeMillis();
        log.info("export success, cost time: {} ms", t2 - t1);
    }
}
